package handler

import (
	"context"
	"github.com/afocus/captcha"
	_ "github.com/astaxie/beego/cache/redis"
	"github.com/astaxie/beego/logs"
	_ "github.com/garyburd/redigo/redis"
	_ "github.com/gomodule/redigo/redis"
	"ihome/utils"
	"image/color"
	"time"

	"github.com/micro/go-micro/util/log"
	getImageCd "ihome/proto/getImageCd"
)

type GetImageCd struct{}

func (e *GetImageCd) SrvGetImageCd(ctx context.Context, req *getImageCd.Request, rsp *getImageCd.Response) error {
	logs.Info("获取验证码图片 SrvGetImageCd /api/v1.0/imagecode/:uuid")

	cap := captcha.New()

	if err := cap.SetFont("comic.ttf"); err != nil {
		panic(err.Error())
	}

	cap.SetSize(91, 41)
	cap.SetDisturbance(captcha.NORMAL)
	cap.SetFrontColor(color.RGBA{R: 255, G: 255, B: 255, A: 255})
	cap.SetBkgColor(color.RGBA{R: 255, A: 255}, color.RGBA{B: 255, A: 255}, color.RGBA{G: 153, A: 255})

	img, str := cap.Create(6, captcha.ALL)

	//redisConf := map[string]string{
	//	"key":   utils.GServerName,
	//	"conn":  utils.GRedisAddr + ":" + utils.GRedisPort,
	//	"dbNum": utils.GRedisDbnum,
	//}
	//logs.Info(redisConf)
	//
	//redisConfJson, _ := json.Marshal(redisConf)
	//
	//bm, err := cache.NewCache("redis", string(redisConfJson))
	bm, err := utils.NewCache()
	if err != nil {
		logs.Info("redis连接失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	///验证码与uuid缓存
	bm.Put(req.Uuid, str, time.Second*300)

	// 图片解引用
	img1 := *img
	img2 := *img1.RGBA

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	rsp.Pix = img2.Pix
	rsp.Stride = int64(img2.Stride)
	rsp.Max = &getImageCd.Response_Point{X: int64(img2.Rect.Max.X), Y: int64(img2.Rect.Max.Y)}
	rsp.Min = &getImageCd.Response_Point{X: int64(img2.Rect.Min.X), Y: int64(img2.Rect.Min.Y)}

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *GetImageCd) Stream(ctx context.Context, req *getImageCd.StreamingRequest, stream getImageCd.GetImageCd_StreamStream) error {
	log.Logf("Received GetImageCd.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&getImageCd.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *GetImageCd) PingPong(ctx context.Context, stream getImageCd.GetImageCd_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&getImageCd.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
